#!/usr/bin/env python

import requests
from shapely.geometry import Point, MultiPoint
import re
from math import cos
from cache import Cache

cache = Cache('lnglat')
GAODE_API_KEY = "87b3f94533c3671a5d727e2742b1a0fc"

KM_1DEG = 111.3195

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36',
}
city_url = 'https://restapi.amap.com/v3/config/district?subdistrict={0}&extensions=all&key={1}&output=json&keywords={2}'

# https://restapi.amap.com/v3/config/district?keywords=%E5%8C%97%E4%BA%AC&subdistrict=2&key=a54d65a9799e7544cb244c9c29c21414

def lnglat(city, distance=2**.5):
    """
    :param city:需要查询的城市
    :return:城市内的符合要求的等距坐标

    """
    list_q = []
    # 根据接口查询城市边界的坐标
    url = city_url.format(0, GAODE_API_KEY, city)
    data = cache.get(url, headers)
    districts = data['districts']
    if not districts:
        return []
    poly_li = []

    for poly in districts[0]['polyline'].split("|"):
        # 将坐标进行处理，获得四个角落的坐标，构造一个矩形网络
        poly_li.extend(tuple(map(float,a.split(','))) for a in poly.split(';'))
    lng_li = [a[0] for a in poly_li]
    lat_li = [a[1] for a in poly_li]
    max_lng = max(lng_li)
    max_lat = max(lat_li)
    min_lng = min(lng_li)
    lat = min(lat_li)

    # print(max_lng, min_lng)
    # print(max_lat, lat)
    # latitude 纬度1°为111.3195km，经度每度为111.3195cos(纬度)
    # # 获得矩形网络内距离为4.2km的所有坐标
    pli = []
    poly = MultiPoint(poly_li).convex_hull
    while lat <= max_lat:
        lat_li.append(lat)
        lng = min_lng
        d = distance/abs(KM_1DEG*cos(lat))
        while lng <= max_lng:
            p = (lng, lat)
            if poly.contains(Point(p)):
                pli.append(p)
            lng += d
        lat += distance/KM_1DEG
    # print(len(pli))
    return pli

